<template>
  <el-card class="box-card">
    <!-- 头部添加按钮 -->
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showTrademarkDialog"
          >添加</el-button
        >
      </div>
    </template>
    <!-- 中间内容部分 -->
    <el-table
      v-loading="loading"
      :data="trademarkList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" align="center" width="80" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 60px; height: 60px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row, $index }">
          <el-button
            size="small"
            type="warning"
            :icon="Edit"
            @click="editTrademark(row)"
          />
          <el-button
            size="small"
            type="danger"
            :icon="Delete"
            @click="removeTrademark(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 底部分页部分 -->
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 20]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper, ->,sizes,total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="添加品牌">
      <el-form
        ref="ruleFormRef"
        :model="trademark"
        :rules="rules"
        :size="formSize"
      >
        <el-form-item
          label="品牌名称"
          prop="tmName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="trademark.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="品牌LOGO"
          prop="logoUrl"
          :label-width="formLabelWidth"
        >
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "Trademark",
}
</script>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue"
import { Plus, Edit, Delete } from "@element-plus/icons-vue"
import {
  reqGetTrademarkListData,
  reqSaveTrademarkInfo,
  reqDeleteTrademarkInfo,
  reqUpdateTrademarkInfo,
} from "@/api/product/trademark"
import type {
  TrademarkMode,
  TrademarkListModel,
} from "@/api/product/model/trademark"
import { ElMessage, ElMessageBox } from "element-plus"
import type { UploadProps, FormInstance, FormRules } from "element-plus"

const currentPage = ref<number>(1) //当前的页码
const pageSize = ref<number>(3) //每页要显示的数量
const trademarkList = ref<TrademarkListModel>([])
const total = ref<number>(0) //总条数
const loading = ref<boolean>(true) //保存loading效果的变量

// 分页相关的变量
const small = ref<boolean>(false)
const background = ref<boolean>(false)
const disabled = ref<boolean>(false)

// 弹窗相关的变量
const BASE_URL = import.meta.env.VITE_API_URL
const dialogFormVisible = ref(false)
const formLabelWidth = "100px"
const initTrademark = () => ({ tmName: "", logoUrl: "" })
const trademark = reactive<TrademarkMode>(initTrademark())

// 弹窗表单校验
const formSize = ref("default")
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    {
      min: 1,
      max: 6,
      message: "输入的品牌名称长度介于1-6个字符",
      trigger: "blur",
    },
  ],
  logoUrl: [{ required: true, message: "请上传图片", trigger: "change" }],
})

//1. 封装调用接口函数的函数
const getTrademarkListData = async () => {
  loading.value = true
  const result = await reqGetTrademarkListData(
    currentPage.value,
    pageSize.value
  )
  trademarkList.value = result.records
  total.value = result.total
  loading.value = false //隐藏loading效果
}

// 2.调用接口获取数据
onMounted(() => {
  getTrademarkListData()
})

// 分页相关的函数
// 3.设置单页几条数据时调用的函数
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`)
  pageSize.value = val
  getTrademarkListData()
}
// 4.跳转当前页码
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`)
  currentPage.value = val
  getTrademarkListData()
}
//  图片上传的两个函数
// 5.图片上传成功后会执行的函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  trademark.logoUrl = response.data
  ruleFormRef.value?.clearValidate("logoUrl") // 如果不写参数 表示清除所有的校验规则
}
// 6.图片上传前的校验函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  const imgFormat = ["image/jpeg", "image/jpg", "image/png"]
  if (!imgFormat.includes(rawFile.type)) {
    ElMessage.error("只能上传png、jpg、jpeg格式的图片")
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传的图片大小不能超过2MB")
    return false
  }
  return true
}

// 7. 实现添加品牌 当前这个确定按钮其实是有两种功能的 一个是添加品牌 一个是更新品牌
const btnTrademark = async () => {
  if (trademark.id) {
    // 执行更新品牌代码
    await reqUpdateTrademarkInfo(trademark)
  } else {
    // 执行添加品牌代码
    await reqSaveTrademarkInfo(trademark)
  }
  ElMessage({
    message: `品牌${trademark.id ? "更新" : "添加"}成功！`,
    type: "success",
  })
  dialogFormVisible.value = false
  currentPage.value = trademark.id ? currentPage.value : 1
  getTrademarkListData()
}
//    添加品牌 拥有表单校验
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    // console.log(valid, fields)
    if (valid) {
      if (trademark.id) {
        // 执行更新品牌代码
        reqUpdateTrademarkInfo(trademark)
      } else {
        // 执行添加品牌代码
        reqSaveTrademarkInfo(trademark)
        currentPage.value = 1
      }
      ElMessage({
        message: `品牌${trademark.id ? "更新" : "添加"}成功！`,
        type: "success",
      })
      dialogFormVisible.value = false
      getTrademarkListData()
    } else {
      console.log("error submit!", fields)
    }
  })
}
// 8. 当单击'添加品牌'按钮时，要弹出对话框 并清空之前的数据
const showTrademarkDialog = () => {
  Object.assign(trademark, initTrademark(), { id: undefined })
  dialogFormVisible.value = true

  // 清除之前的校验规则
  // ruleFormRef.clearValidate() // 如果不写参数 表示清除所有的校验规则
  ruleFormRef.value?.clearValidate() // 如果不写参数 表示清除所有的校验规则
}
// 9. 单击删除按钮 弹出是否删除的提示框 并收集待删除的品牌的id
const removeTrademark = (row: TrademarkMode) => {
  ElMessageBox.confirm(`您确认要删除此品牌吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await reqDeleteTrademarkInfo(row.id as number)
      ElMessage({
        type: "success",
        message: "删除成功",
      })
      currentPage.value =
        trademarkList.value.length > 1
          ? currentPage.value
          : currentPage.value - 1
      getTrademarkListData()
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除...",
      })
    })
}
// 10.单击编辑按钮 弹出是否更新品牌的提示框 并收集更新的品牌数据
const editTrademark = (row: TrademarkMode) => {
  Object.assign(trademark, row)
  dialogFormVisible.value = true
  ruleFormRef.value?.clearValidate() // 清除之前的校验规则
}
</script>

<style scoped>
.el-input {
  width: 75%;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
